package flc.ast.fragment;

import static android.view.Gravity.CENTER;
import static easily.tech.guideview.lib.GuideViewBundle.TransparentOutline.TYPE_RECT;

import android.app.Dialog;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import easily.tech.guideview.lib.GuideViewBundle;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.activity.AlbumActivity;
import flc.ast.activity.MyCollectActivity;
import flc.ast.activity.RecentProjectActivity;
import flc.ast.adapter.AlbumAdapter;
import flc.ast.bean.MyAlbumBean;
import flc.ast.bean.MyCollectBean;
import flc.ast.databinding.FragmentHomeBinding;
import flc.ast.utils.AppSpUtils;
import flc.ast.view.GuideViewFragment;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.view.container.StkLinearLayout;
import stark.common.basic.view.container.StkRelativeLayout;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends BaseNoModelFragment<FragmentHomeBinding> {

    private List<MyAlbumBean> listShow = new ArrayList<>();
    private AlbumAdapter albumAdapter;
    private Dialog myAddAlbumDialog;
    private Dialog myRenameAlbumDialog;
    private EditText dialogAdd;
    private TextView dialogRename;
    private String albumId = "";
    private GuideViewFragment guideViewFragment;
    private List<String> listSel = new ArrayList<>();
    private boolean isEdit = false;


    @Override
    protected int onCreate() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);

        mDataBinding.rvAlbumList.setLayoutManager(new GridLayoutManager(mContext, 2));
        albumAdapter = new AlbumAdapter();
        albumAdapter.setEdit(isEdit);
        mDataBinding.rvAlbumList.setAdapter(albumAdapter);
        albumAdapter.setOnItemClickListener(this);
        albumAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                View item = mDataBinding.rvAlbumList.getChildAt(position);
                StkLinearLayout stkLinearLayout = item.findViewById(R.id.llAlbumItem);
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(500, 1000);
                guideViewFragment = new GuideViewFragment.Builder()
                        .addGuidViewBundle(new GuideViewBundle.Builder()
                                .setTargetView(stkLinearLayout)
                                .setHintView(null)
                                .setMaskColor(Color.parseColor("#B00E0F12"))
                                .setDismissOnClicked(true)
                                .setHintViewMargin(0, 0, 0, 0)
                                .setTransparentSpace(-25, 75, -15, -115)
                                .setOutlineType(TYPE_RECT)
                                .setHintViewParams(params)
                                .setHintViewDirection(CENTER).build())
                        .setCancelable(true)
                        .build();
                guideViewFragment.show(getChildFragmentManager(), "hit");
                albumId = albumAdapter.getItem(position).getId();
                guideViewFragment.setListener(new GuideViewFragment.Listener() {
                    @Override
                    public void clickCancel() {
                        guideViewFragment.dismiss();
                    }

                    @Override
                    public void clickDelete() {
                        delete();
                        guideViewFragment.dismiss();
                    }

                    @Override
                    public void clickRename() {
                        //重命名相册弹框
                        renameAlbumDialog();
                        myRenameAlbumDialog.show();
                        guideViewFragment.dismiss();
                    }
                });
                return false;
            }
        });
        mDataBinding.rlAddAlbum.setOnClickListener(this);
        mDataBinding.ivAlbumManage.setOnClickListener(this);
        mDataBinding.tvAlbumManageCancel.setOnClickListener(this);
        mDataBinding.rlRecentProject.setOnClickListener(this);
        mDataBinding.rlMyCollect.setOnClickListener(this);

        HomeActivity.tvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listSel.size() == 0) {
                    ToastUtils.showShort(getString(R.string.please_sel_album));
                    return;
                }
                deleteList();
            }
        });
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.rlAddAlbum://新建相册
                //新建相册弹框
                addAlbumDialog();
                myAddAlbumDialog.show();
                break;
            //新建相册弹框
            case R.id.tvDialogAddAlbumConfirm://确定
                addAlbum();
                break;
            case R.id.ivDialogAddAlbumCancel://取消
                myAddAlbumDialog.dismiss();
                break;
            case R.id.ivAlbumManage://管理
                isEdit = true;
                albumAdapter.setEdit(isEdit);
                mDataBinding.ivAlbumManage.setVisibility(View.INVISIBLE);
                mDataBinding.tvAlbumManageCancel.setVisibility(View.VISIBLE);
                HomeActivity.rlDelete.setVisibility(View.VISIBLE);
                HomeActivity.tvDelete.setText(getString(R.string.delete_album_num, 0));
                break;
            case R.id.tvAlbumManageCancel://取消管理
                isEdit = false;
                albumAdapter.setEdit(isEdit);
                mDataBinding.ivAlbumManage.setVisibility(View.VISIBLE);
                mDataBinding.tvAlbumManageCancel.setVisibility(View.INVISIBLE);
                HomeActivity.rlDelete.setVisibility(View.GONE);
                listSel.clear();
                break;
            //重命名相册弹框
            case R.id.tvDialogRenameAlbumConfirm:
                rename();
                break;
            case R.id.ivDialogRenameAlbumCancel:
                myRenameAlbumDialog.dismiss();
                break;
            case R.id.rlRecentProject://最近项目
                startActivity(RecentProjectActivity.class);
                break;
            case R.id.rlMyCollect://我的收藏
                startActivity(MyCollectActivity.class);
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (isEdit) {
            if (albumAdapter.getItem(position).isSelected()) {
                albumAdapter.getItem(position).setSelected(false);
                listSel.remove(albumAdapter.getItem(position).getId());
            } else {
                albumAdapter.getItem(position).setSelected(true);
                listSel.add(albumAdapter.getItem(position).getId());
            }
            HomeActivity.tvDelete.setText(getString(R.string.delete_album_num, listSel.size()));
            albumAdapter.notifyItemChanged(position);
        } else {
            AlbumActivity.albumId = albumAdapter.getItem(position).getId();
            startActivity(AlbumActivity.class);
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        if (StkPermissionHelper.hasGrantMediaImgVideoPermission()) {
            getPictureSize();
        } else {
            mDataBinding.tvProjectNum.setText("0");
        }
        getCollectSize();
        getData();
    }

    private void getData() {
        listShow.clear();
        List<MyAlbumBean> listSp = AppSpUtils.getAlbumList();
        if (listSp != null && listSp.size() > 0) {
            listShow.addAll(listSp);
            mDataBinding.tvAlbumSize.setText(getString(R.string.album_num, listShow.size()));
            albumAdapter.setList(listShow);
            mDataBinding.rvAlbumList.setVisibility(View.VISIBLE);
            mDataBinding.tvAlbumNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.tvAlbumSize.setText(getString(R.string.album_num, listShow.size()));
            mDataBinding.rvAlbumList.setVisibility(View.GONE);
            mDataBinding.tvAlbumNoData.setVisibility(View.VISIBLE);
        }
    }

    //获取视频和图片数据
    private void getPictureSize() {
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.PHOTO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    mDataBinding.tvProjectNum.setText(selectMediaEntities.size() + "");
                } else {
                    mDataBinding.tvProjectNum.setText("0");
                }
            }
        });
    }

    //获取我的收藏图片数量
    private void getCollectSize() {
        List<MyCollectBean> listSp = AppSpUtils.getCollectList();
        if (listSp != null && listSp.size() > 0) {
            mDataBinding.tvCollectNum.setText(listSp.size() + "");
        } else {
            mDataBinding.tvCollectNum.setText("0");
        }
    }

    private void addAlbum() {
        String albumName = dialogAdd.getText().toString();
        if (TextUtils.isEmpty(albumName)) {
            ToastUtils.showShort(R.string.please_input_album_name);
            return;
        }
        myAddAlbumDialog.dismiss();
        //准备数据
        List<MyAlbumBean> listSave = new ArrayList<>();
        listSave.add(new MyAlbumBean(TimeUtils.getNowString(), albumName, new ArrayList<>(), false));
        //保存数据
        List<MyAlbumBean> listSp = AppSpUtils.getAlbumList();
        if (listSp != null && listSp.size() > 0) {
            listSp.addAll(listSave);
            AppSpUtils.saveAlbumList(listSp);
        } else {
            AppSpUtils.saveAlbumList(listSave);
        }
        getData();
    }

    //删除相册
    private void delete() {
        List<MyAlbumBean> listSp = AppSpUtils.getAlbumList();
        if (listSp != null && listSp.size() > 0) {
            for (int i = 0; i < listSp.size(); i++) {
                if (listSp.get(i).getId().equals(albumId)) {
                    listSp.remove(i);
                    break;
                }
            }
            AppSpUtils.saveAlbumList(listSp);
            ToastUtils.showShort(getString(R.string.delete_suc));
        }
        getData();
    }

    //多个删除相册
    private void deleteList() {
        List<MyAlbumBean> listSp = AppSpUtils.getAlbumList();
        if (listSp != null && listSp.size() > 0) {
            Iterator<MyAlbumBean> iterator = listSp.iterator();
            while (iterator.hasNext()) {
                MyAlbumBean item = iterator.next();
                for (String s : listSel) {
                    if (item.getId().equals(s)) {
                        iterator.remove();
                        break;
                    }
                }
            }
            AppSpUtils.saveAlbumList(listSp);
            ToastUtils.showShort(getString(R.string.delete_suc));
        }
        isEdit = false;
        albumAdapter.setEdit(isEdit);
        getData();
        mDataBinding.ivAlbumManage.setVisibility(View.VISIBLE);
        mDataBinding.tvAlbumManageCancel.setVisibility(View.INVISIBLE);
        HomeActivity.rlDelete.setVisibility(View.GONE);
        listSel.clear();
    }

    //重命名
    private void rename() {
        String albumName = dialogRename.getText().toString();
        if (TextUtils.isEmpty(albumName)) {
            ToastUtils.showShort(R.string.please_input_album_name);
            return;
        }
        myRenameAlbumDialog.dismiss();
        List<MyAlbumBean> listSp = AppSpUtils.getAlbumList();
        if (listSp != null && listSp.size() > 0) {
            for (int i = 0; i < listSp.size(); i++) {
                if (listSp.get(i).getId().equals(albumId)) {
                    listSp.get(i).setName(albumName);
                    break;
                }
            }
            AppSpUtils.saveAlbumList(listSp);
            ToastUtils.showShort(getString(R.string.save_success));
        }
        getData();
    }

    //新建相册弹框
    private void addAlbumDialog() {
        myAddAlbumDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_album, null);
        myAddAlbumDialog.setContentView(inflate);
        myAddAlbumDialog.setCancelable(true);
        Window dialogWindow = myAddAlbumDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogAddAlbumConfirm);
        ImageView cancel = inflate.findViewById(R.id.ivDialogAddAlbumCancel);
        TextView num = inflate.findViewById(R.id.tvDialogAddAlbumNum);
        num.setText(getString(R.string.input_name_num, 0));
        dialogAdd = inflate.findViewById(R.id.etDialogAddAlbumText);
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
        dialogAdd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                num.setText(getString(R.string.input_name_num, s.length()));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    //重命名相册弹框
    private void renameAlbumDialog() {
        myRenameAlbumDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_rename_album, null);
        myRenameAlbumDialog.setContentView(inflate);
        myRenameAlbumDialog.setCancelable(true);
        Window dialogWindow = myRenameAlbumDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogRenameAlbumConfirm);
        ImageView cancel = inflate.findViewById(R.id.ivDialogRenameAlbumCancel);
        TextView num = inflate.findViewById(R.id.tvDialogRenameAlbumNum);
        num.setText(getString(R.string.input_name_num, 0));
        dialogRename = inflate.findViewById(R.id.etDialogRenameAlbumText);
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
        dialogRename.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                num.setText(getString(R.string.input_name_num, s.length()));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

}